package com.xxx.mch.service.impl;

import com.xxx.mch.dao.BusinessStatisticsMapper;
import com.xxx.mch.dao.DepartmentMapper;
import com.xxx.mch.dao.TaskScoreTemplateMapper;
import com.xxx.mch.dao.UserMapper;
import com.xxx.mch.domain.dto.UserResultScoreDto;
import com.xxx.mch.domain.po.BusinessStatistics;
import com.xxx.mch.domain.po.Department;
import com.xxx.mch.domain.po.ResultScore;
import com.xxx.mch.domain.po.ResultScoreTemplate;
import com.xxx.mch.domain.po.SystemConfig;
import com.xxx.mch.domain.po.TaskScoreTemplate;
import com.xxx.mch.domain.po.TotalScore;
import com.xxx.mch.domain.po.User;
import com.xxx.mch.exception.BusinessException;
import com.xxx.mch.service.ScoreService;
import com.xxx.mch.service.SystemConfigService;
import com.xxx.mch.service.TotalScoreService;
import java.math.BigDecimal;
import java.math.RoundingMode;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class BusinessStatisticsImpl
{

    @Autowired
    private BusinessStatisticsMapper businessStatisticsMapper;

    @Autowired
    private TaskScoreTemplateMapper taskScoreTemplateMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private TotalScoreService totalScoreService;

    @Resource
    private ScoreService<ResultScore, ResultScoreTemplate> scoreService;

    @Autowired
    private SystemConfigService systemConfigService;


    public List<LinkedHashMap<String, String>> queryBusinessStatistics(String month, Integer deptId, String uid)
    {
        List<TaskScoreTemplate> taskScoreTemplateList = taskScoreTemplateMapper.selectSecondaryTemplate();
        //list中每个item表示一个人
        List<LinkedHashMap<String, String>> list = businessStatisticsMapper.selectBusinessStatistics(taskScoreTemplateList, month, deptId,
                                                                                                     uid);
        this.fill(list, month);

        return list;
    }


    private void fill(List<LinkedHashMap<String, String>> list, String month)
    {
        Map<String, SystemConfig> scoreWeight = systemConfigService.queryConfigByMenu("scoreWeight");
        BigDecimal determinationScoreWeight = scoreWeight.get("determinationScore").getValue().divide(new BigDecimal("100"), 2,
                                                                                                      RoundingMode.DOWN);
        BigDecimal allowanceScoreWeight = scoreWeight.get("allowanceScore").getValue().divide(new BigDecimal("100"), 2, RoundingMode.DOWN);

        list.forEach(detailMap -> {
            //归档量 TODO 来源
            detailMap.put("archiveCount", "0");
            TotalScore personalScoreDto = totalScoreService.queryTotalScore(detailMap.get("uid"), month);
            boolean isNUll = Objects.isNull(personalScoreDto);
            //定量分。。。
            detailMap.put("qualityScore", isNUll ? "0" : personalScoreDto.getAllowanceScore().toPlainString());
            //定性分
            detailMap.put("determinationScore", isNUll ?
                    "0" :
                    personalScoreDto.getDeterminationScore()
                                    .add(Objects.isNull(personalScoreDto.getDeltaScore()) ?
                                                 BigDecimal.ZERO :
                                                 personalScoreDto.getDeltaScore())
                                    .toPlainString());
            //总分 = 定量 + 定性 ? 还是直接去表中的中分
            detailMap.put("totalScore", isNUll ? "0" : personalScoreDto.getDeterminationScore()
                                                                       .multiply(determinationScoreWeight)
                                                                       .add(personalScoreDto.getAllowanceScore()
                                                                                            .multiply(allowanceScoreWeight))
                                                                       .add(Objects.isNull(personalScoreDto.getDeltaScore()) ?
                                                                                    BigDecimal.ZERO :
                                                                                    personalScoreDto.getDeltaScore())
                                                                       .toPlainString());
            //本月奖金
            detailMap.put("money", isNUll ? "0" : personalScoreDto.getMoney().toPlainString());

            UserResultScoreDto userResultScoreDto = scoreService.queryUserScore(detailMap.get("uid"), month);
            //阅读量
            detailMap.put("readCount", userResultScoreDto.getReadCount().toString());
            //获奖量
            detailMap.put("awardCount", userResultScoreDto.getAwardCount().toString());
            //表扬量
            detailMap.put("praiseCount", userResultScoreDto.getPraiseCount().toString());
            //其他量，已投中石油 + 已投社会媒体 之和
            int other = userResultScoreDto.getPetroChinaCount() + userResultScoreDto.getSocialMediaCount();
            detailMap.put("otherCount", String.valueOf(other));
            //本月积分
            detailMap.put("points", isNUll ? "0" : personalScoreDto.getPoints().toPlainString());
            //累计积分,计算累计积分
            detailMap.put("accumulativePoints", totalScoreService.queryAccumulativePoints(detailMap.get("uid")).toPlainString());
        });

    }


    public int saveBusinessStatistics(BusinessStatistics bs)
    {
        User user = userMapper.selectOne(new User().setUserCode(bs.getUid()));
        if (user == null)
        {
            throw new BusinessException("当前用户不存在：usercode=" + bs.getUid());
        }
        Department department = departmentMapper.selectOne(new Department().setId(user.getDeptId()));
        if (department == null)
        {
            throw new BusinessException("当前部门不存在：deptId=" + user.getDeptId());
        }
        bs.setUsername(user.getNickName());
        bs.setDeptName(department.getOrganizationName());
        bs.setDeptId(user.getDeptId());
        return businessStatisticsMapper.insertSelective(bs);
    }
}
